package com.superbit.service.match.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.superbit.core.constant.QuoteOrderConstant;
import com.superbit.core.entry.Coin_Base_Info;
import com.superbit.core.exception.BusinessException;
import com.superbit.core.service.MarketService;
import com.superbit.core.vo.CoinTypeVO;
import com.superbit.service.coin.define.Coin_Base_InfoService;
@Service(value = "marketService")
public class MarketServiceImpl implements MarketService {

	@Autowired
	private Coin_Base_InfoService coin_Base_InfoService;
	
	@Autowired
	private TradeLogProxyImpl tradeLogProxyImpl; 
	
	@Transactional
	@Override
	public List<CoinTypeVO> getCoinMarketInfo() throws BusinessException {
		//TODO 获取所有审核通过的币种
		List<CoinTypeVO> coinVoList = new ArrayList<CoinTypeVO>();
		List<Coin_Base_Info> coin_Base_InfoList = coin_Base_InfoService.getCoin_Base_InfoList(1, null, null, null);
		if(coin_Base_InfoList == null ||coin_Base_InfoList.size() == 0){
			throw new BusinessException("CM001", "no examine coin", null);
		}
		for (Coin_Base_Info coin_Base_Info : coin_Base_InfoList) {
			CoinTypeVO coinTypeVo = new CoinTypeVO();
			String coinCode = coin_Base_Info.getCoinCode();
			BigDecimal newTradeCNY = tradeLogProxyImpl.getNewTradeCNY(coinCode);
			coinTypeVo.setCoinCode(coinCode);
			coinTypeVo.setCoinArea(coin_Base_Info.getArea());
			coinTypeVo.setCoinId(coin_Base_Info.getId());//TODO 需要确认对应的id是否是coinId
			coinTypeVo.setCoinName(coin_Base_Info.getCoinName());
			//涨幅
			coinTypeVo.setLastestPrice(newTradeCNY.toString());
			coinTypeVo.setIncrease(this.getIncrease(newTradeCNY, tradeLogProxyImpl.getLastDayTradeCNY(coinCode)));//TODO new BigDecimal("1000.23")) tradeLogProxyImpl.getLastDayTradeCNY(coinCode))
			coinVoList.add(coinTypeVo);
		}
		return coinVoList;
	}
	
	
	
	/**
	 * 获取涨幅
	 * @param lastPrice 最新价
	 * @param lastDayPrice 上一天24点前最后一笔成交价
	 * @return 涨幅
	 */
	private String getIncrease(BigDecimal lastPrice,BigDecimal lastDayPrice)throws BusinessException{
		BigDecimal zeroP = new BigDecimal(0);
		if(lastDayPrice.compareTo(zeroP) == 0 | lastPrice.compareTo(zeroP) == 0){
			return "0.00";
		}
		if(lastPrice == null || lastDayPrice == null){
			throw new BusinessException("QO006", "deal price is exception", null);
		}
		BigDecimal multi = lastPrice.subtract(lastDayPrice).setScale(QuoteOrderConstant.QUOTE_CNY_ACCURAY, BigDecimal.ROUND_HALF_EVEN);
		BigDecimal setScale = multi.divide(lastDayPrice,QuoteOrderConstant.QUOTE_CNY_ACCURAY, BigDecimal.ROUND_HALF_EVEN);
		return setScale.multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_EVEN).toString();
	}

}
